import com.fasterxml.jackson.databind.ObjectMapper;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

class Message2 {
    public String from;
    public String to;
    public String message;

    @Override
    public String toString() {
        return "Message2{" +
                "from='" + from + '\'' +
                ", to='" + to + '\'' +
                ", message='" + message + '\'' +
                '}';
    }
}

@WebServlet("/message2")
public class MessageServlet2 extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    // 用来存储客户端上的消息
    private File messageFile = new File("D:/javacode/frontend/message.txt");

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 读取前端发来的请求，并将数据存储到文件上
        Message2 message = objectMapper.readValue(req.getInputStream(), Message2.class);
        System.out.println("请求中的数据: " + message);

        // 2. 将数据存储到文件上
        String messageJson = objectMapper.writeValueAsString(message);
        try (FileWriter write = new FileWriter(messageFile,true)){
            write.write(messageJson + "\n");
        }

        // 3. 给客户端返回响应
        resp.setStatus(200);
        resp.setContentType("application/json; charset=utf8");
        resp.getWriter().write("ok");
    }



    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 将文件中的 json字符串 放到 messageList中
        List<Message2> messagesList = new ArrayList<>();
        try(Scanner scanner = new Scanner(messageFile)) {
            while(scanner.hasNext()) {
                String messageJson = scanner.next();
                Message2 message = objectMapper.readValue(messageJson,Message2.class);
                messagesList.add(message);
            }
        }

        // 2. 将 messageList 中的所有 Message对象转换成 json字符串数组  返回给客户端
        resp.setStatus(200);
        resp.setContentType("application/json; charset=utf8");
        String respJson = objectMapper.writeValueAsString(messagesList);
        resp.getWriter().write(respJson);

    }
}
